import React, { useEffect, useState } from 'react';
import { Link, Outlet } from 'react-router-dom';
import { HomeFilled, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import { Menu } from 'antd'
import { storage } from '@/utils'
import './index.scss'
type mType = {
    key: any,
    label: React.ReactNode,
    children?: mType[],
    icon: React.ReactNode
}

function Index() {
    let [aMenu, setAmenu] = useState<mType[]>([]);
    let [collapsed, setCollapsed] = useState(false)
    let [hW, setHw] = useState(0);
    useEffect(() => {
        //读取menu数据
        let menu = JSON.parse(storage("fuint-menu"))
        let psMenu = patter(menu, []);
        setAmenu(psMenu);
        setHw(window.innerWidth - (!collapsed ? 200 : 80));
        function resizeFun(): void {
            let iw = window.innerWidth;
            setHw(iw - (!collapsed ? 200 : 80));
        }
        window.addEventListener("resize", resizeFun)
        return () => {
            window.removeEventListener("resize", resizeFun)
        }
    }, [collapsed])

    //点击切换状态
    let changeStaus = () => {
        setCollapsed(!collapsed);
    }

    //解析数据menu
    let patter = (arr: menuType, target: mType[]): mType[] => {
        if (!arr) return [];
        arr.forEach((item, index) => {
            let o: mType = {
                key: item.path,
                icon: <HomeFilled />,
                label: item.component === "Layout" ? item.meta.title : <Link to={item.path}>{item.meta.title}</Link>,
            }
            if (item.children && !item.hidden) {
                o.children = patter(item.children, []);
                if (!o.children.length)
                    delete o.children;
            }
            !item.hidden && target.push(o)
        })
        return target;
    }
    return (
        <div className='admin'>
            <div className='admin-silder' style={{ width: `${!collapsed ? 200 : 80}px` }}>
                <Menu
                    defaultSelectedKeys={['1']}
                    defaultOpenKeys={['sub1']}
                    mode="inline"
                    theme="dark"
                    inlineCollapsed={collapsed}
                    items={aMenu}
                />
            </div>
            <div className='admin-header' style={{ left: `${!collapsed ? 200 : 80}px`, width: `${hW}px` }}>
                <div className='admin-header-top'>
                    {!collapsed ? <MenuFoldOutlined onClick={changeStaus} className='icon' /> : <MenuUnfoldOutlined onClick={changeStaus} className='icon' />}
                </div>
                <div className='admin-header-history'>
                    历史记录
                </div>
            </div>
            <div className='admin-content' style={{ marginLeft: `${!collapsed ? 200 : 80}px` }}>
                <Outlet />
            </div>
        </div>
    );
}

export default Index;